#include "Message.h"
#include <iostream>

using std::cout;
using std::endl;

Message::Message(){}

Message::~Message(){}

// 设置发送 Json
void Message::setMsgSendJson(int msgLen, int msgType, string msgCon){
    _msgSend["len"] = msgLen;
    _msgSend["type"] = msgType;
    _msgSend["content"] = msgCon;
    _msgSendLen = _msgSend.dump().length();
}

// 设置接收 Json
void Message::setMsgRecvJson(char* msgCon){
    _msgRecv = nlohmann::json::parse(msgCon); 
}

// 获取发送的信息
string Message::getMsgSendCon(){
    return _msgSend.dump();
} 

// 获取发送消息的长度
int Message::getMsgSendLen(){
    return _msgSendLen;
}

int* Message::getMsgSendLenPtr(){
    return &_msgSendLen;
}
   
// 获取接收消息的长度
int Message::getMsgRecvLen(){
    return _msgRecvLen;
}

int* Message::getMsgRecvLenPtr(){
    return &_msgRecvLen;
}


void Message::handleMsgRecv(){
    if(_msgRecv.at("type") == 100){ // 关键字
        cout <<"搜索结果: "
            << _msgRecv.at("content")
            << endl; 
    }
    else if(_msgRecv.at("type") == 200){ // 网页
        cout << "搜索结果:" << endl ;
        if(_msgRecv.contains("content")){
            cout<<" "<<_msgRecv["content"] << endl;
        }
        else{
            cout << endl;
            string count_s;
            int pageNum = _msgRecv.at("len");
            for(int i = 1; i <= pageNum; i++){
                count_s = std::to_string(i);
                string title = "title";   
                string link = "link";   
                string description = "description";   
                cout<< "《" << _msgRecv[title += count_s].get<string>()<< "》"<< endl; 
                for(int i = 0; i < 4; i++){
                    cout << "**********************";
                } 
                cout << endl;
                cout<< " [ "<< _msgRecv[link += count_s].get<string>()<<" ] "<< endl; 
                for(int i = 0; i < 4; i++){
                    cout << "**********************";
                } 
                cout << endl;
                cout<< "【文章简介】" << endl << _msgRecv[description += count_s].get<string>() << endl; 
                cout << endl;
                cout << endl;
                cout << endl;
            } 
        }      
    }
    else{
        cout << "消息接收错误！"<< endl;
    }
}
